<?php

namespace app\admin\controller;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use think\App;
use think\facade\Db;
use app\admin\model\{ Users, Orders };

/**
 * Class Admin
 * @package app\admin\controller
 * @ControllerAnnotation(title="工资管理")
 */
class Wages extends AdminController
{

    protected $noExportFileds = ['create_time', 'update_time', 'bank'];

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Wages();
        
        $this->assign('getStatusList', $this->model->getStatusList());

    }

    /**
     * @NodeAnotation(title="工资结算")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $where[] = ['status', '=', 0];
            $count = Users::where($where)->count();
            $list = Users::where($where)
                    ->hidden(['password'])
                    ->page($page, $limit)
                    ->order('uid','desc')
                    ->select();
            foreach ($list as $k => $v){
                $all = $v['base_salary'] + $v['ratio_amount'] + $v['bonus_amount'];
                $list[$k]['all_amount'] = $all ? '+'.$all : $all;
                $list[$k]['base_salary'] = $v['base_salary'] > 0 ? '+'.$v['base_salary'] : $v['base_salary'];
                $list[$k]['ratio_amount'] = $v['ratio_amount'] > 0 ? '+'.$v['ratio_amount'] : $v['ratio_amount'];
                $list[$k]['bonus_amount'] = $v['bonus_amount'] > 0 ? '+'.$v['bonus_amount'] : $v['bonus_amount'];
                $list[$k]['wage_time'] = is_null($list[$k]['wage_time']) ? '无' : date('Y-m-d H:i:s', $v['wage_time']);
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="已发列表")
     */
    public function index2()
    {
        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 强行非关联搜索where拦截
            foreach ($where as $k => $v){
                if ($v[0] == 'true_name'){
                    $where[$k] = whereHook($v, 'uid', '\app\admin\model\Users','uid');
                }
            }
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            foreach ($list as $k => $v){
                $user = Users::where('uid', $v['uid'])->find();
                $list[$k]['true_name'] = $user->true_name;
                $list[$k]['job_number'] = $user->job_number;
                $list[$k]['wage_time'] = is_null($list[$k]['wage_time']) ? '无' : date('Y-m-d H:i:s', $v['wage_time']);
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="批量工资结算")
     */
    public function generate()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'base_date1|基本工资起始日期'      =>  'require|date',
                'base_date2|基本工资截止日期'      =>  'require|date',
                'date|提成截止日期'                =>  'require|date',
                'bonus_date|奖金月份'              =>  'require|date',
            ];
            $this->validate($post, $rule);
            $post['date'] = $post['date'].' 23:59:59';
            $post['base_date2'] = $post['base_date2'].' 23:59:59';
            if (strtotime($post['base_date2']) < strtotime($post['base_date1'])){
                $this->error('基本工资截止日期不能小于起始日期');
            }
            $users = Users::where('status',0)->field('uid,job_number,true_name,base_salary,entry_date')->select();
            $users->isEmpty() && $this->error('请先添加员工');
            $temp_orders = [];
            $ranking = ranking(2,3, $post['bonus_date']);
            foreach ($users as $k => $v){
                $ratio_amount = 0;
                $bonus_amount = 0;
                $v['base_salary'] = getTrueBaseSalary($v, strtotime($post['base_date1']), strtotime($post['base_date2']));

                if (!empty($ranking)){
                    if (isset($ranking[0]) && $ranking[0]['num'] > 0 && $ranking[0]['uid'] == $v['uid']){
                        $bonus_amount = 1500;
                    }
                    if (isset($ranking[1]) && $ranking[1]['num'] > 0 && $ranking[1]['uid'] == $v['uid']){
                        $bonus_amount = 1000;
                    }
                    if (isset($ranking[2]) && $ranking[2]['num'] > 0 && $ranking[2]['uid'] == $v['uid']){
                        $bonus_amount = 500;
                    }
                }
                $users[$k]['bonus_amount'] = $bonus_amount;
                $orders = Orders::whereTime('success_time','<=', $post['date'])->where(['uid' => $v['uid'], 'state' => 1])->select();
                $users[$k]['wage_time'] = time();
                if ($orders->isEmpty()){
                    $users[$k]['ratio_amount'] = 0;
                    $users[$k]['all_amount'] = $v['base_salary'] + $bonus_amount;
                    continue;
                }
                foreach ($orders as $a => $b){
                    $amount = $b['pay_amount'] * $b['ratio'] / 100;
                    $ratio_amount += $amount;
                    $temp_orders[$a]['id'] = $b['id'];
                    $temp_orders[$a]['ratio_amount'] = $amount;
                }
                $users[$k]['ratio_amount'] = $ratio_amount;
                $users[$k]['all_amount'] = $v['base_salary'] + $ratio_amount + $bonus_amount;
            }
            Db::startTrans();
            try {
                $this->model->saveAll($users->toArray());
                if (!empty($temp_orders)){
                    foreach ($temp_orders as $k => $v){
                        Orders::update([
                            'state'         =>  2,
                            'ratio_amount'  =>  $v['ratio_amount'],
                            'ratio_time'    =>  time(),
                        ],[
                            'id'            =>  $v['id'],
                        ]);
                    }
                }
                foreach ($users as $k => $v){
                    Users::update([
                        'ratio_amount'  =>  $v['ratio_amount'],
                        'bonus_amount'  =>  $v['bonus_amount'],
                        'all_amount'    =>  $v['all_amount'],
                        'wage_time'     =>  time(),
                    ],[
                        'uid'           =>  $v['uid'],
                    ]);
                }
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                $this->error('生成失败：'.$e->getMessage());
            }
            $this->success('生成成功');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="个体工资结算")
     */
    public function generateOne()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'uid|用户uid'                     =>  'require|number',
                'base_date1|基本工资起始日期'      =>  'require|date',
                'base_date2|基本工资截止日期'      =>  'require|date',
                'date|提成截止日期'                =>  'require|date',
                'bonus_date|奖金月份'              =>  'require|date',
            ];
            $this->validate($post, $rule);
            $post['date'] = $post['date'].' 23:59:59';
            $post['base_date2'] = $post['base_date2'].' 23:59:59';
            if (strtotime($post['base_date2']) < strtotime($post['base_date1'])){
                $this->error('基本工资截止日期不能小于起始日期');
            }
            $user = Users::where(['status' => 0, 'uid' => $post['uid']])->field('uid,job_number,true_name,base_salary,entry_date')->find();
            empty($user) && $this->error('员工不存在');
            $temp_orders = [];
            $ratio_amount = 0;
            $bonus_amount = 0;
            $user['base_salary'] = getTrueBaseSalary($user, strtotime($post['base_date1']), strtotime($post['base_date2']));
            $ranking = ranking(2,3, $post['bonus_date']);
            if (!empty($ranking)){
                if (isset($ranking[0]) && $ranking[0]['num'] > 0 && $ranking[0]['uid'] == $user['uid']){
                    $bonus_amount = 1500;
                }
                if (isset($ranking[1]) && $ranking[1]['num'] > 0 && $ranking[1]['uid'] == $user['uid']){
                    $bonus_amount = 1000;
                }
                if (isset($ranking[2]) && $ranking[2]['num'] > 0 && $ranking[2]['uid'] == $user['uid']){
                    $bonus_amount = 500;
                }
            }
            $user['bonus_amount'] = $bonus_amount;
            $user['wage_time'] = time();
            $orders = Orders::whereTime('success_time','<=', $post['date'])->where(['uid' => $user['uid'], 'state' => 1])->select();
            if ($orders->isEmpty()){
                $user['ratio_amount'] = 0;
                $user['all_amount'] = $user['base_salary'] + $bonus_amount;
            }else{
                foreach ($orders as $a => $b){
                    $amount = $b['pay_amount'] * $b['ratio'] / 100;
                    $ratio_amount += $amount;
                    $temp_orders[$a]['id'] = $b['id'];
                    $temp_orders[$a]['ratio_amount'] = $amount;
                }
                $user['ratio_amount'] = $ratio_amount;
                $user['all_amount'] = $user['base_salary'] + $ratio_amount + $bonus_amount;
            }
            Db::startTrans();
            try {
                \app\admin\model\Wages::create($user->toArray());
                if (!empty($temp_orders)){
                    foreach ($temp_orders as $k => $v){
                        Orders::update([
                            'state'         =>  2,
                            'ratio_amount'  =>  $v['ratio_amount'],
                            'ratio_time'    =>  time(),
                        ],[
                            'id'            =>  $v['id'],
                        ]);
                    }
                }
                Users::update([
                    'ratio_amount'  =>  $user['ratio_amount'],
                    'bonus_amount'  =>  $user['bonus_amount'],
                    'all_amount'    =>  $user['all_amount'],
                    'wage_time'     =>  time(),
                ],[
                    'uid'           =>  $user['uid'],
                ]);
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                $this->error('生成失败：'.$e->getMessage());
            }
            $this->success('生成成功');
        }
        $this->assign('row', Users::find($this->request->param('uid/d')));
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        list($page, $limit, $where) = $this->buildTableParames();
		$where[] = ['status', '=', 0];
        $arr = [
            '序号','付款方客户账号','付款方账户名称','收款方行别代码','收款方客户账号',
            '收款方账户名称','收款方开户行名称','收款方联行号','客户方流水号','金额',
            '用途','备注','是否短信通知收款人','收款人手机号码','短信通知附加信息',
        ];
        $header = [];
        foreach ($arr as $k => $v) {
            $header[] = [$v, 'key'.$k, 'text'];
        }
        $count = Users::where($where)->count();
        $list = Users::where($where)
            ->limit($count)
            ->order('create_time','desc')
            ->select()
            ->toArray();
        foreach ($list as $k => $v){
            $user = Users::find($v['uid']);
            if ($user->status == 1){
                unset($list[$k]);
                continue;
            }
            $res[$k]['key0'] = $k + 1;
            $res[$k]['key1'] = '45050159004200000262';
            $res[$k]['key2'] = '广西南宁软甲士网络科技有限公司';
            $res[$k]['key3'] = ($user->bank == 3) ? '01' : '02';
            $res[$k]['key4'] = $user->bank_account;
            $res[$k]['key5'] = $user->true_name;
            if ($user->bank <> 3 && empty($user->bank_name)){
                $this->error('员工：'.$user->true_name.' 使用非建设银行卡，个人资料中必须填写支行！');
            }
            $res[$k]['key6'] = $user->bank_name;;
            $res[$k]['key7'] = '';
            $res[$k]['key8'] = '';
            $res[$k]['key9'] = $v['all_amount'];
            $res[$k]['key10'] = '工资';
            $res[$k]['key11'] = '';
            $res[$k]['key12'] = '0';
            $res[$k]['key13'] = '';
            $res[$k]['key14'] = '';
        }
        $filename = date('Y-m-d', time());
        return Excel::exportData($res, $header, $filename, 'xlsx', true);
    }
}